<script setup lang="ts">
import { ref, watch, onMounted } from "vue";
import { invoke } from "@tauri-apps/api/core";
import type { ApiResponse } from "../types";

const inputTimestamp = ref<string>('');
const outputTimestamp = ref<string>('');
const timestampUnit = ref<string>('seconds');
const showTimestampButtons = ref<boolean>(false);
const inputDatetime = ref<string>('');
const outputDatetime = ref<string>('');
const selectedTimezone = ref<string>('+08:00');
const datetimeUnit = ref<string>('seconds');
const currentTimestamp = ref<string>('');
const currentDatetime = ref<string>('');

// 自动判断时间戳单位
const autoDetectTimestampUnit = (value: string) => {
  const timestamp = parseInt(value);
  if (isNaN(timestamp)) return;
  
  if (timestamp > 10000000000) {
    timestampUnit.value = 'milliseconds';
  } else {
    timestampUnit.value = 'seconds';
  }
};

// 监听输入变化
watch(inputTimestamp, (newValue) => {
  autoDetectTimestampUnit(newValue);
});

// 获取当前时区偏移
const getCurrentTimezoneOffset = () => {
  const date = new Date();
  const offset = -date.getTimezoneOffset();
  const hours = Math.floor(Math.abs(offset) / 60);
  const minutes = Math.abs(offset) % 60;
  const sign = offset >= 0 ? '+' : '-';
  return `${sign}${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}`;
};

// 初始化时区
selectedTimezone.value = getCurrentTimezoneOffset();

const timestampToDatetime = async () => {
  try {
    const timestamp = parseInt(inputTimestamp.value);
    if (isNaN(timestamp)) {
      outputTimestamp.value = '错误：请输入有效的时间戳';
      return;
    }

    const response = await invoke<ApiResponse>("timestamp_to_datetime", {
      timestamp,
      isMilliseconds: timestampUnit.value === 'milliseconds'
    });
    
    if (response.success) {
      outputTimestamp.value = response.result;
    } else {
      outputTimestamp.value = `错误：${response.error}`;
    }
  } catch (error) {
    outputTimestamp.value = `错误：${error}`;
  }
};

const datetimeToTimestamp = async () => {
  try {
    const response = await invoke<ApiResponse>("datetime_to_timestamp", {
      datetimeStr: inputDatetime.value,
      isMilliseconds: datetimeUnit.value === 'milliseconds',
      timezone: selectedTimezone.value
    });
    
    if (response.success) {
      outputDatetime.value = response.result;
    } else {
      outputDatetime.value = `错误：${response.error}`;
    }
  } catch (error) {
    outputDatetime.value = `错误：${error}`;
  }
};

// 更新当前时间戳
const updateCurrentTimestamp = () => {
  const now = Date.now();
  currentTimestamp.value = now.toString();
  
  const date = new Date(now);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  const milliseconds = String(date.getMilliseconds()).padStart(3, '0');
  currentDatetime.value = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}.${milliseconds}`;
};

// 启动定时器
onMounted(() => {
  updateCurrentTimestamp();
  setInterval(updateCurrentTimestamp, 1000);
});

const copyCurrentTimestamp = () => {
  inputTimestamp.value = currentTimestamp.value;
};

const copyCurrentDatetime = () => {
  inputDatetime.value = currentDatetime.value;
};

const adjustTimestamp = (amount: number) => {
  const currentValue = parseInt(inputTimestamp.value) || 0;
  const newValue = currentValue + amount;
  inputTimestamp.value = newValue.toString();
  timestampToDatetime();
};
</script>

<template>
  <div>
    <h1 class="module-title">时间戳转换工具</h1>
    
    <!-- Unix时间戳 → 时间 -->
    <div class="timestamp-section">
      <div class="section-header">
        <h2 class="section-title">Unix时间戳 → 时间</h2>
        <div class="current-timestamp" @click="copyCurrentTimestamp" title="点击复制到输入框">
          当前时间戳：{{ currentTimestamp }}
        </div>
      </div>
      <div class="conversion-container">
        <div class="input-group">
          <div class="timestamp-input-wrapper"
            @mouseenter="showTimestampButtons = true"
            @mouseleave="showTimestampButtons = false"
          >
            <input 
              v-model="inputTimestamp"
              type="text"
              placeholder="请输入Unix时间戳..."
              class="timestamp-input"
            />
            <div class="timestamp-buttons" v-show="showTimestampButtons">
              <button class="timestamp-adjust-btn" @click="adjustTimestamp(1)" title="增加1">▲</button>
              <button class="timestamp-adjust-btn" @click="adjustTimestamp(-1)" title="减少1">▼</button>
            </div>
          </div>
          <select v-model="timestampUnit" class="unit-select">
            <option value="seconds">秒</option>
            <option value="milliseconds">毫秒</option>
          </select>
          <button @click="timestampToDatetime" class="format-button">转换</button>
        </div>
        <div class="output-group">
          <div class="output-label">转换结果：</div>
          <textarea
            v-model="outputTimestamp"
            placeholder="转换结果将显示在这里..."
            class="text-output"
            readonly
          ></textarea>
        </div>
      </div>
    </div>

    <!-- 时间 → Unix时间戳 -->
    <div class="timestamp-section">
      <div class="section-header">
        <h2 class="section-title">时间 → Unix时间戳</h2>
        <div class="current-datetime" @click="copyCurrentDatetime" title="点击复制到输入框">
          当前时间：{{ currentDatetime }}
        </div>
      </div>
      <div class="conversion-container">
        <div class="input-group">
          <input 
            v-model="inputDatetime"
            type="text"
            placeholder="请输入时间（格式：YYYY-MM-DD HH:mm:ss.SSS）..."
            class="timestamp-input"
          />
        </div>
        <div class="control-group">
          <select v-model="selectedTimezone" class="timezone-select">
            <option value="+08:00">UTC+08:00 (北京时间)</option>
            <option value="+00:00">UTC+00:00 (格林威治时间)</option>
            <option value="-08:00">UTC-08:00 (太平洋时间)</option>
            <option value="-05:00">UTC-05:00 (东部时间)</option>
          </select>
          <select v-model="datetimeUnit" class="unit-select">
            <option value="seconds">秒</option>
            <option value="milliseconds">毫秒</option>
          </select>
          <button @click="datetimeToTimestamp" class="format-button">转换</button>
        </div>
        <div class="output-group">
          <div class="output-label">转换结果：</div>
          <textarea
            v-model="outputDatetime"
            placeholder="转换结果将显示在这里..."
            class="text-output"
            readonly
          ></textarea>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.module-title {
  font-size: 18px;
  font-weight: 500;
  color: #2c3e50;
  margin-bottom: 12px;
}

.section-title {
  font-size: 15px;
  font-weight: 500;
  color: #2c3e50;
  margin: 0 0 10px 0;
}

.timestamp-section {
  background-color: #fff;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.timestamp-section h2 {
  font-size: 16px;
  margin: 0 0 15px 0;
  color: #333;
}

.conversion-container {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.input-group {
  display: flex;
  gap: 10px;
  align-items: center;
}

.timestamp-input-wrapper {
  position: relative;
  flex: 1;
}

.timestamp-buttons {
  position: absolute;
  right: 6px;
  top: 50%;
  transform: translateY(-50%);
  display: flex;
  flex-direction: column;
  gap: 0;
  background-color: rgba(255, 255, 255, 0.95);
  border-radius: 3px;
  padding: 1px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(0, 0, 0, 0.1);
}

.timestamp-adjust-btn {
  width: 20px;
  height: 12px;
  padding: 0;
  border: none;
  background-color: transparent;
  color: #666;
  font-size: 8px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 0;
  transition: all 0.2s ease;
  line-height: 1;
}

.timestamp-adjust-btn:first-child {
  border-bottom: 1px solid rgba(0, 0, 0, 0.1);
}

.timestamp-adjust-btn:hover {
  background-color: #4CAF50;
  color: white;
}

.timestamp-input {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 12px;
  transition: all 0.3s ease;
}

.timestamp-input:hover {
  border-color: #4CAF50;
}

.timestamp-input:focus {
  outline: none;
  border-color: #4CAF50;
  box-shadow: 0 0 0 2px rgba(76, 175, 80, 0.2);
}

.unit-select, .timezone-select {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 12px;
  background-color: white;
  min-width: 100px;
  color: #333;
  cursor: pointer;
  transition: all 0.3s ease;
  appearance: none;
  background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%23666' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3e%3cpolyline points='6 9 12 15 18 9'%3e%3c/polyline%3e%3c/svg%3e");
  background-repeat: no-repeat;
  background-position: right 8px center;
  background-size: 16px;
  padding-right: 32px;
}

.timezone-select {
  min-width: 180px;
}

.unit-select:hover, .timezone-select:hover {
  border-color: #4CAF50;
}

.unit-select:focus, .timezone-select:focus {
  outline: none;
  border-color: #4CAF50;
  box-shadow: 0 0 0 2px rgba(76, 175, 80, 0.2);
}

.control-group {
  display: flex;
  gap: 10px;
  align-items: center;
  margin-top: 10px;
  justify-content: flex-end;
}

.output-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.output-label {
  font-size: 12px;
  color: #666;
}

.text-output {
  width: 100%;
  height: 60px;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', monospace;
  font-size: 12px;
  line-height: 1.4;
  resize: none;
  background-color: #f8f9fa;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.current-timestamp, .current-datetime {
  font-size: 12px;
  color: #666;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', monospace;
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.current-timestamp:hover, .current-datetime:hover {
  background-color: rgba(76, 175, 80, 0.1);
}

.format-button {
  background-color: #4CAF50;
  color: white;
  padding: 6px 16px;
  border: none;
  border-radius: 4px;
  font-size: 13px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.format-button:hover {
  background-color: #45a049;
}

@media (prefers-color-scheme: dark) {
  .module-title {
    color: #ecf0f1;
  }

  .section-title {
    color: #ecf0f1;
  }

  .timestamp-section {
    background-color: #2d2d2d;
  }

  .timestamp-section h2 {
    color: #fff;
  }

  .timestamp-buttons {
    background-color: rgba(45, 45, 45, 0.95);
    border-color: rgba(255, 255, 255, 0.1);
  }

  .timestamp-adjust-btn {
    color: #999;
  }

  .timestamp-adjust-btn:first-child {
    border-bottom-color: rgba(255, 255, 255, 0.1);
  }

  .timestamp-input, .unit-select, .timezone-select {
    background-color: #2d2d2d;
    border-color: #404040;
    color: #ffffff;
  }

  .unit-select, .timezone-select {
    background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%23fff' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3e%3cpolyline points='6 9 12 15 18 9'%3e%3c/polyline%3e%3c/svg%3e");
  }

  .text-output {
    background-color: #2d2d2d;
    color: #ffffff;
    border-color: #404040;
  }

  .output-label {
    color: #999;
  }

  .current-timestamp, .current-datetime {
    color: #999;
  }
  
  .current-timestamp:hover, .current-datetime:hover {
    background-color: rgba(76, 175, 80, 0.2);
  }

  .format-button {
    background-color: #4CAF50;
  }

  .format-button:hover {
    background-color: #45a049;
  }
}
</style> 